// 由于 package.json 中设置了 "type": "module"，我们需要使用 ES 模块格式
import { createServer } from 'http';
import { readFile, access } from 'fs/promises';
import { constants } from 'fs';
import { join, extname } from 'path';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// 获取当前文件的目录
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

const PORT = 8080;
const DIST_DIR = join(__dirname, 'dist');

const MIME_TYPES = {
  '.html': 'text/html',
  '.js': 'text/javascript',
  '.css': 'text/css',
  '.json': 'application/json',
  '.png': 'image/png',
  '.jpg': 'image/jpg',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.svg': 'image/svg+xml',
  '.ico': 'image/x-icon',
  '.woff': 'font/woff',
  '.woff2': 'font/woff2',
  '.ttf': 'font/ttf',
  '.eot': 'application/vnd.ms-fontobject',
  '.otf': 'font/otf'
};

createServer(async (req, res) => {
  console.log(`Request: ${req.url}`);

  // 处理URL
  let url = req.url;
  
  // 首页重定向到哈希模式路由
  if (url === '/') {
    url = '/index.html';
  }

  // 解析文件路径
  const filePath = join(DIST_DIR, url);
  const ext = extname(filePath).toLowerCase();
  const contentType = MIME_TYPES[ext] || 'application/octet-stream';

  try {
    // 检查文件是否存在
    await access(filePath, constants.F_OK);
    
    // 文件存在，返回文件内容
    const data = await readFile(filePath);
    res.writeHead(200, { 'Content-Type': contentType });
    res.end(data);
  } catch (err) {
    try {
      // 文件不存在，尝试返回 index.html (SPA通常需要这样处理)
      const indexPath = join(DIST_DIR, 'index.html');
      const data = await readFile(indexPath);
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(data);
    } catch (indexErr) {
      // index.html 也不存在
      res.writeHead(404);
      res.end('404 Not Found');
    }
  }
}).listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
  console.log(`Static files served from: ${DIST_DIR}`);
}); 